﻿using AspectCore.DynamicProxy;
using AspectCore.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace AspectCoreProj
{
    class Program
    {
        static void Main(string[] args)
        {
            //https://github.com/dotnetcore/AspectCore-Framework/blob/master/docs/0.AOP%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D.md

            //IOC容器
            ServiceCollection services = new ServiceCollection();

            //注册服务
            //services.AddDynamicProxy();
            services.ConfigureDynamicProxy();

            

            services.AddTransient<IMySql, MySql>();

            var provider = services.BuildAspectInjectorProvider();

            var mysql = provider.GetService<IMySql>();

            var str1 = mysql.GetData(10);

            var str2 = mysql.GetData(10);

            Console.WriteLine($"str1:{str1},str2:{str2}");

            Console.ReadKey();


        }
    }

    public class MyCacheInterceptorAttribute:AbstractInterceptorAttribute
    {
        public static Dictionary<string, object> RedisDict = new Dictionary<string, object>();

        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var cacheKey = string.Join(",", context.Parameters);
            if (RedisDict.ContainsKey(cacheKey))
            {
                context.ReturnValue = RedisDict[cacheKey];
                return Task.CompletedTask;
            }

            var task = next(context);

            var cacheValue = context.ReturnValue;

            RedisDict.Add(cacheKey, cacheValue);

            return task;
        }
    }


    public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
    {
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Console.WriteLine("开始记录日志。。。。。");

            var task = next(context);

            Console.WriteLine("结束记录日志。。。。。");

            return task;
        }
    }
    public interface IMySql
    {
        string GetData(int id);
    }

    public class MySql : IMySql
    {
        [MyCacheInterceptor]
        [MyLogInterceptor]
        public string GetData(int id)
        {
            var msg = $"已经获取到数据id={id}的数据";

            Console.WriteLine(msg);

            return msg;
        }
    }
}
